<?php

class SwapsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'offer', 'IsOffered', 'DisOffer', 'AcceptOffer', 'IsCreator', 'IsAccepted', 'delete'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$condition = "swap_id=$id";
		$dataProvider=new CActiveDataProvider('swapOffers', array(
		'criteria'=>array(
		'condition'=>$condition,
		),
		));

	
		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'dataProvider'=>$dataProvider,
		));
	}

	//check the swap is offered by the loged in usr
	public function actionIsOffered($id)
	{
		$uid=Yii::app()->user->id;
		
		$sql = "select * from swap_offers where swap_id=$id AND user_id=$uid"; 
				$command = Yii::app()->db->createCommand($sql);   
				$data=$command->queryAll();	
		
		if ($data == null)
		{
			return 0;
		}
		else
		{
			return 1;
		}
	} 
	
	//check the user is the Creator of the swap
	public function actionIsCreator($id)
	{
		$uid=Yii::app()->user->id;
		
		$sql = "select * from swaps where creator_id=$uid AND id=$id"; 
				$command = Yii::app()->db->createCommand($sql);   
				$data=$command->queryAll();	
		
		if ($data == null)
		{
			return 0;
		}
		else
		{
			return 1;
		}
	}
	
	//check is there offer with status = 2
	public function actionIsAccepted ($id)
	{
		$uid=Yii::app()->user->id;
		
		$sql = "select * from swap_offers where swap_id=$id AND status=2"; 
				$command = Yii::app()->db->createCommand($sql);   
				$data=$command->queryAll();	
		
		if ($data == null)
		{
			return 0;
		}
		else
		{
			return 1;
		}
	}
	
	
	// Delete Offer
	public function actionDisOffer($id)
	{	
		$uid=Yii::app()->user->id;
		$model=$this->loadModel($id);
		
		$condition = "swap_id=$id";
		$dataProvider=new CActiveDataProvider('swapOffers', array(
		'criteria'=>array(
		'condition'=>$condition,
		),
		));
	
		$sql = "DELETE FROM swap_offers WHERE swap_id=$id AND user_id=$uid";
		$command = Yii::app()->db->createCommand($sql);     
		$data=$command->execute();	
		
		$this->redirect(array('view','id'=>$id));
	
		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'dataProvider'=>$dataProvider,
		));	
	}
	
	// Accept offer
	public function actionAcceptOffer($id)
	{	
		$uid=Yii::app()->user->id;
		$model=$this->loadModel($id);
	
		$condition = "swap_id=$id";
		$dataProvider=new CActiveDataProvider('swapOffers', array(
		'criteria'=>array(
		'condition'=>$condition,
		),
		));
	
		# change offer status to 2
		$sql = "UPDATE swap_offers SET status=2 WHERE swap_id=$id AND user_id=$uid";
		$command = Yii::app()->db->createCommand($sql);     
		$data=$command->execute();	
	
		$rid=$model->creator_id;
		$mid=2;
	
		# send message to creator
		$mail = ComposeController::actionComposeAuto($mid, $uid, $rid);
	
		$this->redirect(array('view','id'=>$id));
		
		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'dataProvider'=>$dataProvider,
		));	
	}
	
	public function actionCreate()
	{
		$uid=Yii::app()->user->id;
		$model=new Swaps;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Swaps']))
		{
			$model->attributes=$_POST['Swaps'];
			$model->date=new CDbExpression('NOW()');
			$model->creator_id=$uid;
			
			$image=CUploadedFile::getInstance($model,'pictures_path');
			$image_dir = '/files/';
			$image_filename = round(microtime(true) * 1000) . '.jpg';
			$model->pictures_path = $image_dir . $image_filename;

			if($model->save()){
				if (!file_exists($image_dir))
					mkdir($image_dir);
				
				//$image->saveAs($model->pictures_path);
				
				$this->redirect(array('view','id'=>$model->id));
				}
		}
		

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Swaps']))
		{
			$model->attributes=$_POST['Swaps'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	public function actionOffer($id)
	{	
		//$model=$this->loadModel($id);
		$uid=Yii::app()->user->id;
		$model_offer=new SwapOffers;
		
		$swap = $this->loadModel($id);
		
		if(isset($_POST['SwapOffers']))
		{
			$model_offer->attributes=$_POST['SwapOffers'];
			$model_offer->date=new CDbExpression('NOW()');
			$model_offer->user_id=$uid;
			$model_offer->swap_id=$id;
			$model_offer->status=1;
			if($model_offer->save())
				$this->redirect(array('view','id'=>$id));
			
			//new offer arrived mail
			$mail = ComposeController::actionComposeAuto($mid, $uid, $rid);
				
		}
		
		$model=$this->loadModel($id);
		$rid=$model->creator_id;
		$mid=1;
		
			
		$this->render('offer',array(
			'model'=>$model_offer,
			'swap'=>$swap, 
			)
		);	
	}
	
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
	
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(array('index'));
	}
	

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Swaps', array(
			'pagination'=>array(
                'pageSize'=>10,
			),
		));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Swaps('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Swaps']))
			$model->attributes=$_GET['Swaps'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Swaps::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='swaps-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
